package com.shou.service.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shou.BusinessException;
import com.shou.CommonVar;
import com.shou.dao.AdministratorDao;
import com.shou.entity.Administrator;
import com.shou.util.CipherUtil;
import com.shou.util.RandomValidateCode;

@Service("administratorService")
public class AdministratorService {
	
	
	
	@Autowired
	AdministratorDao administratorDaoImpl;
	
	public void login(HttpServletRequest request, String username,String password,String validate){
		
		String validateSession = (String)request.getSession().getAttribute(RandomValidateCode.RANDOMCODEKEY);
		if(!validate.equalsIgnoreCase(validateSession)) {
			throw new BusinessException("验证码错误");
		}
		Administrator administrator = administratorDaoImpl.getBy(Administrator.class,"username",username);
		if(administrator!=null){
			if(administrator.getPassword().equalsIgnoreCase(CipherUtil.encode(password))){
				request.getSession().setAttribute(CommonVar.SESSION_ADMIN, administrator);
			}
			else {
				throw new BusinessException("密码错误");
			}
		}
		else {
			throw new BusinessException("该用户不存在");
		}
	}
	
	public void modifyPwd(HttpServletRequest request,String opassword,String password1) {
		Administrator administrator = (Administrator)request.getSession().getAttribute(CommonVar.SESSION_ADMIN);
		if(administrator!=null && administrator.getPassword().equals(CipherUtil.encode(opassword))){
			administrator.setPassword(CipherUtil.encode(password1));
			administratorDaoImpl.saveOrUpdate(administrator);
			request.getSession().setAttribute(CommonVar.SESSION_ADMIN, administrator);
		} else {
			throw new BusinessException("输入的登录密码有误！");
		}
	}
}
